package com.credit.anypermission

import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import androidx.annotation.CheckResult
import androidx.core.app.ActivityCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.credit.anypermission.permission.PermissionsHelper

object AnyPermission {

    @CheckResult
    @JvmStatic
    fun init(activity: FragmentActivity): PermissionsHelper {
        return PermissionsHelper().setActivity(activity)
    }

    @CheckResult
    @JvmStatic
    fun init(fragment: Fragment): PermissionsHelper {
        return PermissionsHelper().setFragment(fragment)
    }

    @CheckResult
    @JvmStatic
    fun init(context: Context): PermissionsHelper {
        return PermissionsHelper().setContext(context)
    }

    @JvmStatic
    fun hasPermissions(context: Context, vararg permissions: String): Boolean {
        for (permission in permissions) {
            if (ActivityCompat.checkSelfPermission(
                    context,
                    permission
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                return false
            }
        }
        return true
    }

    /**
     * 判断某个权限是否被永久拒绝
     */
    @JvmStatic
    fun isPermissionPermanentDenied(context: Context, permission: String?): Boolean {
        val permissionApi = Class.forName("com.hjq.permissions.PermissionApi")
        val constructor = permissionApi.getDeclaredConstructor()
        constructor.isAccessible = true
        val permissionApiObj = constructor.newInstance()
        val permanentDeniedMethod = permissionApi.getDeclaredMethod(
            "isPermissionPermanentDenied",
            Activity::class.java,
            String::class.java
        )
        permanentDeniedMethod.isAccessible = true
        return permanentDeniedMethod.invoke(permissionApiObj, context, permission) as Boolean
    }


}